
#include <string.h>

#include "Des.h"

#include "ISO14443Command.h"
#include "CardCommandDefine.h"
#include "CardCommand.h"
//PICC
#include "CardPort.h"
#include "CardPrivate.h"
#include "ISO14443p3b.h"
#include "CardMem.h"
//ICC
#include "Driver.h"
#include "Bsp.h"
#include "IDCard/ID_Process.h"

#include "Reader.h"

#include "Env.h"

#include "Debug.h"


int Reader_DetectTypeB(int timeout){
	ISO14443BInfo_T info;
	
	ISO14443B_SetMode(0);
	return ISO14443B_WakeupB(0, &info) == 0;
}


static int Reader_SFZ_GetUID(CSN_T* csn){
	ISO14443BInfo_T info;
	unsigned char resp [16];
	unsigned int rlen;
	
	ISO14443B_SetMode(0);
	int ret = ISO14443B_WakeupB(0, &info);
	if (ret) {
		return -200;
	}
	ret = ISO14443B_ATTRIB(0, info.atqb + 1, 0, resp, &rlen);
	if (ret) {
		return -2;
	}
	
	uint8_t capdu[] = {0x00, 0x36, 0x00, 0x00, 0x08};
	memset(resp, 0, sizeof(resp));
	rlen = 0;
	ret = WCI_Exchange(0, capdu, sizeof(capdu), resp, &rlen, 16, WaitTime_Ms(50, 0), WaitTime_Ms(1, 0));			
	if (ret) {
		return -3;
	}
	
	if(rlen == 10 && (resp[rlen - 2] == 0x90 && resp[rlen - 1] == 0x00)){
		memcpy(csn->num, resp, 8);
		csn->nlen = 8;
		csn->info = 0;
		csn->std = Card_T_CpuB;
		return 0;
	}
	return -4;
}

static int Reader_SFZ_GetInfo(CSN_T* csn){
	WCI_SetRf(0, 0);
	BSP_Delay_ms(10);
	WCI_SetRf(0, 1);
	ISO14443B_SetMode(0);
	BSP_Delay_ms(10);
	
	Buffer_T resp = {
		.buffer = csn->ibuf,
	};
	int ret = ID_ReadInfo(&resp);
	if(ret){
		return ret;
	}
	csn->ilen = resp.length;
	csn->info = 1;
	return ret;
}


int Reader_ReadTypeB(CSN_T* csn){
	int ret = Reader_SFZ_GetUID(csn);
	if(ret){
		return ret;
	}
	
	csn->ilen = 0;
	if(Flag_IsSet(envData.rdSupport[1], ENV_Func_SFZ)){
		ret = Reader_SFZ_GetInfo(csn);
	}
	return ret;
}


